﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Data;
using SilverNotes.Common;

namespace SilverNotes
{
  public class MainPageViewModel : ViewModelBase
  {
    private IViewDescriptor _selectedView;
    private List<IViewDescriptor> _allItems;

    public IViewDescriptor SelectedItem
    {
      get { return _selectedView; }
      set
      {
        _selectedView = value;
        OnPropertyChanged("SelectedItem");
      }
    }

    private FilterItem _selectedFilter;

    public FilterItem SelectedFilter
    {
      get { return _selectedFilter; }
      set
      {
        _selectedFilter = value;
        //var selectedItem = SelectedItem;
        Items.Clear();
        foreach (var item in _allItems)
        {
          if (_selectedFilter == null || _selectedFilter.Filter(item))
          {
            Items.Add(item);
          }
        }
        OnPropertyChanged("SelectedFilter");
        //if (selectedItem != null && Items.Count > 0)
        //{
        //  SelectedItem = Items[0];
        //}
      }
    }

    public ObservableCollection<FilterItem> Filters
    {
      get; private set;
    }

    public ObservableCollection<IViewDescriptor> Items
    {
      get; private set;
    }

    public MainPageViewModel(IEnumerable<IViewDescriptor> pluggedDescriptors)
    {
      var allFilter = new FilterItem("All", item => true);
      Filters = new ObservableCollection<FilterItem>
                  {
                    allFilter
                  };
      Items = new ObservableCollection<IViewDescriptor>();
      _allItems = new List<IViewDescriptor>();
      var hashSet = new HashSet<string>();
      foreach (var pluggedDescriptor in pluggedDescriptors)
      {
        var category = pluggedDescriptor.Category;
        if (!string.IsNullOrEmpty(category) && !hashSet.Contains(category))
        {
          hashSet.Add(category);
          Filters.Add(new FilterItem(category, view => SortByGroupName(view, category)));
        }
        var item = pluggedDescriptor;
        if (item is UIElement)
        {
          item = new DescriptorWrapper(pluggedDescriptor);
        }
        _allItems.Add(item);
      }
      //SelectedItem = Items[0];
      SelectedFilter = Filters[0];
    }

    private static bool SortByGroupName(IViewDescriptor view, string name)
    {
      return view != null && view.Category == name;
    }
  }
}